package de.cwach.svgeditor;

import java.util.LinkedList;
import java.util.logging.*;

public class StringUndoHistory {

	private static Logger logger = Logger
			.getLogger("de.cwach.svgeditor.StringUndoHistory");

	private int size;

	private LinkedList<String> undo, redo;

	public StringUndoHistory(int size) {
		undo = new LinkedList<String>();
		redo = new LinkedList<String>();
		this.size = size;
	}

	public String undo(String r) {

		if (undo.isEmpty()) {
			return null;
		}

		// store redo information
		if (redo.isEmpty() || !r.equals(redo.getFirst())) {
			redo.addFirst(r);
		}

		String result = undo.removeFirst();

		if (!result.equals(r)) {
			return result;
		} else if (undo.isEmpty()) {
			return null;
		} else {
			return undo.removeFirst();
		}
	}

	public String redo(String r) {

		if (redo.isEmpty())
			return null;
		// Store only, if new string is different from previous undo string
		if (undo.isEmpty() || !r.equals(undo.getFirst())) {
			undo.addFirst(r);
		}
		return redo.removeFirst();

	}

	public void setUndoPoint(String s) {
		if (undo.size() >= size) {
			undo.removeLast();
		}
		// Store only, if new string is different from previous undo string
		if (undo.isEmpty() || !s.equals(undo.getFirst())) {
			undo.addFirst(s);
			logger.fine("creating new undo point");
		} else {
			logger.fine("no new undo information");
		}
	}
}
